<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title>角色管理 - xx管理系统</title>

  <!-- Favicons -->
  <link href="assets/img/favicon.png" rel="icon">

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="assets/vendor/gridjs/dist/theme/mermaid.min.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
</head>

<body>

  <!-- ======= Header ======= -->
  <header id="header" class="header fixed-top d-flex align-items-center">
    <div class="d-flex align-items-center justify-content-between">
      <a href="index.html" class="logo d-flex align-items-center">
        <img src="assets/img/logo.png" alt="">
        <span class="d-none d-lg-block">XX管理系统</span>
      </a>
      <i class="bi bi-list toggle-sidebar-btn"></i>
    </div>

    <nav class="header-nav ms-auto">
      <ul class="d-flex align-items-center">
        <li class="nav-item dropdown pe-3">
          <a class="nav-link nav-profile d-flex align-items-center pe-0" href="#" data-bs-toggle="dropdown">
            <img src="assets/img/profile-img.jpg" alt="Profile" class="rounded-circle">
            <span class="d-none d-md-block dropdown-toggle ps-2">用户名</span>
          </a>
          <ul class="dropdown-menu dropdown-menu-end dropdown-menu-arrow profile">
            <li class="dropdown-header">
              <h6 id="deptmentName">部门名</h6>
              <span id="roleName">角色名</span>
            </li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li>
              <a class="dropdown-item d-flex align-items-center" href="personal.html">
                <i class="bi bi-gear"></i>
                <span>个人信息</span>
              </a>
            </li>
            <li>
              <hr class="dropdown-divider">
            </li>
            <li>
              <a class="dropdown-item d-flex align-items-center" href="#">
                <i class="bi bi-box-arrow-right"></i>
                <span>注销登录</span>
              </a>
            </li>
          </ul>
        </li>
      </ul>
    </nav>
  </header>

  <!-- ======= Sidebar ======= -->
  <aside id="sidebar" class="sidebar">
    <ul class="sidebar-nav" id="sidebar-nav">
      <li class="nav-item">
        <a class="nav-link collapsed" href="index.html">
          <i class="bi bi-grid"></i>
          <span>个人主页</span>
        </a>
      </li>

      <li class="nav-item">
        <a class="nav-link" data-bs-target="#components-nav" data-bs-toggle="collapse" href="#">
          <i class="bi bi-menu-button-wide"></i><span>系统管理</span><i class="bi bi-chevron-down ms-auto"></i>
        </a>
        <ul id="components-nav" class="nav-content" data-bs-parent="#sidebar-nav">
          <li><a href="system-user.html"><i class="bi bi-circle"></i><span>用户管理</span></a></li>
          <li><a href="system-dept.html"><i class="bi bi-circle"></i><span>部门管理</span></a></li>
          <li><a href="system-role.html" class="active"><i class="bi bi-circle"></i><span>角色管理</span></a></li>
        </ul>
      </li>
      <li class="nav-item">
        <a class="nav-link collapsed" href="blank.html">
          <i class="bi bi-file-earmark"></i>
          <span>空白模板页</span>
        </a>
      </li>
    </ul>
  </aside>

  <main id="main" class="main">
    <div class="pagetitle">
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">主页</a></li>
          <li class="breadcrumb-item">系统管理</li>
          <li class="breadcrumb-item active">角色管理</li>
        </ol>
      </nav>
    </div>

    <section class="section">
      <div class="row">
        <div class="col-lg-12">
          <div class="card">
            <div class="card-body">
              <h5 class="card-title">角色列表</h5>
              <form id="searchForm" class="row row-cols-lg-auto g-3 mb-3 align-items-center">
                <div class="col-12">
                  <input type="text" class="form-control" name="name" placeholder="角色名称" />
                </div>
                <div class="col-12">
                  <button type="submit" class="btn btn-primary"><i class="bi bi-search"></i>查询</button>
                  <button type="reset" class="btn btn-secondary"><i class="bi bi-arrow-repeat"></i>重置</button>
                  <button id="createRoleButton" type="button" class="btn btn-success"><i
                      class="bi bi-plus"></i>添加</button>
                </div>
              </form>
              <div id="dataTable"></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </main>

  <!-- Footer -->
  <footer id="footer" class="footer">
    <div class="credits">Designed by 2022030202033-曾广生</div>
  </footer>

  <!-- Success Toast -->
  <div class="toast-container position-absolute top-0 end-0">
    <div id="successToastEl" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true"
      style="color: #fff;background-color: #19875488;">
      <div class="toast-body"><i class="bi bi-check-circle"></i><span id="successMessage">操作成功！</span></div>
    </div>
  </div>

  <!-- Edit Modal -->
  <div class="modal fade" id="editRoleModalEl" tabindex="-1" aria-hidden="true">
    <form id="editRoleForm" class="needs-validation" novalidate>
      <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">编辑角色</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>

          <div class="modal-body">
            <div id="editRoleAlert"></div>
              <input type="text" class="form-control" id="id" name="id" required hidden/>
            <div class="mb-3">
              <label for="name" class="form-label">角色名称</label>
              <input type="text" class="form-control" id="name" name="name" required />
            </div>
            <div class="mb-3">
              <label for="type" class="form-label">角色类型</label>
              <input type="text" class="form-control" id="type" name="type" required />
            </div>
            <div class="mb-3">
              <label for="enableState" class="form-label">状态</label>
              <input type="text" class="form-control" id="enableState" name="enableState" />
            </div>
            <div class="mb-3">
              <label for="deptType" class="form-label">所属部门类型</label>
              <input type="text" class="form-control" id="deptType" name="deptType" required />
            </div>
            <div class="mb-3">
              <label for="dataScope" class="form-label">数据访问范围</label>
              <input type="text" class="form-control" id="dataScope" name="dataScope" required />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            <button type="submit" class="btn btn-primary">提交</button>
          </div>
        </div>
      </div>
    </form>
  </div>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/gridjs/dist/gridjs.umd.js"></script>
  <script src="assets/vendor/moment/moment.js"></script>

  <script>
    // 定义中文本地化配置
    const cnCN = {
      search: {
        placeholder: '搜索...'
      },
      pagination: {
        previous: '上一页',
        next: '下一页',
        showing: '显示',
        results: () => '条结果'
      },
      loading: '加载中...',
      noRecordsFound: '没有找到匹配的记录',
      error: '加载数据时发生错误',
    };
    const url = "/api/rest/role/all"; // 更新 URL 以指向正确的端点
    let roles = [];

    const columns = [
      { id: "name", name: "角色名称" },
      { id: "id", name: "编号", width: "10%" },
      { id: "type", name: "类型" },
      { id: "enableState", name: "状态" },
      { id: "createAt", name: "创建时间" },
      {
        name: "操作",
        width: "20%",
        formatter: (_, row) => {
          const enableState = row.cells[3].data; // 获取状态
          const buttonText = enableState === "启用" ? "禁用" : "启动";
          const buttonClass = enableState === "启用" ? "btn-danger" : "btn-success";
          const iconClass = enableState === "启用" ? "bi-slash-circle" : "bi-check-circle";

          return gridjs.html(`
        <button class="updateRoleButton btn btn-sm btn-primary m-1" data-id="${row.cells[1].data}">
          <i class="bi bi-pencil-square"></i> 编辑
        </button>
        <button class="toggleRoleButton btn btn-sm ${buttonClass} m-1" data-id="${row.cells[1].data}">
          <i class="bi ${iconClass}"></i> ${buttonText}
        </button>
      `);
        },
      },
    ];


    const gridOptions = {
      columns,
      server: {
        url,  // 使用更新后的 URL
        then: data => {
          roles = data;
          return data.map(item => [
            item.name,
            item.id,
            item.type,
            item.enableState,
            item.createAt ? moment(item.createAt).format("YYYY-MM-DD HH:mm:ss") : ""
          ]);
        },
        total: data => data.totalElements,
      },
      pagination: true,
      language: cnCN,
    };


    window.onload = function () {
      
      let roleId = null;
      fetch("api/rest/self")
      .then(response => response.json())
      .then(data =>{
        roleId = data.id;
        document.getElementById("deptmentName").innerText = data.dept.name;
        document.getElementById("name").innerText = data.name;
        document.getElementById("roletName").innerText = data.role.name;
        if(data.avator){
          document.getElementById("userAvatarImg").src = `/api/rest/attachment/${data.avatar}`;
        } else{
          document.getElementById("userAvatarImg").src = `assets/img/user.png`;
        }
      }
    )
      const grid = new gridjs.Grid(gridOptions).render(document.getElementById("dataTable"));
      let isEditMode = false; // 用于判断当前是否是编辑模式
      let currentRoleId = null; // 保存当前编辑的角色ID


      // “添加”按钮点击事件，打开模态框并清空表单
      document.getElementById("createRoleButton").addEventListener("click", () => {
        isEditMode = false; // 设置为添加模式
        currentRoleId = null; // 清空当前角色ID
        document.getElementById("editRoleForm").reset(); // 清空表单内容
        new bootstrap.Modal(document.getElementById("editRoleModalEl")).show();
      });
      // 表格中编辑按钮点击事件
      document.getElementById("dataTable").addEventListener("click", (event) => {
        if (event.target.closest(".updateRoleButton")) {
          isEditMode = true; // 设置为编辑模式
          currentRoleId = event.target.closest(".updateRoleButton").getAttribute("data-id"); // 获取角色ID
          const role = roles.find(r => r.id == currentRoleId); // 查找当前角色的数据

          if (role) {
            // 填充表单
            document.getElementById("id").value = role.id;
            document.getElementById("name").value = role.name;
            document.getElementById("type").value = role.type;
            document.getElementById("enableState").value = role.enableState || '';
            new bootstrap.Modal(document.getElementById("editRoleModalEl")).show();
          }
        }
      });
      document.getElementById("editRoleModalEl").addEventListener("hidden.bs.modal", function () {
        document.body.classList.remove("modal-open");
        document.body.style.overflow = "auto";
        document.querySelectorAll(".modal-backdrop").forEach(backdrop => backdrop.remove());
      });

      document.getElementById("searchForm").addEventListener("submit", async (event) => {
        event.preventDefault();

        const formData = new FormData(document.getElementById("searchForm"));
        const name = formData.get("name").trim();
        const type = formData.get("type");
        const enableState = formData.get("enableState");

        try {
          const response = await fetch(url);
          const data = await response.json();

          let filteredData = data.filter(item => {
            return (
              (!name || item.name.includes(name)) &&
              (!type || item.type === type) &&
              (!enableState || item.enableState === enableState)
            );
          });

          filteredData = {
            content: filteredData,
            totalElements: filteredData.length
          };

          const server = {
            url,
            then: () => {
              return filteredData.content.map(item => [
                item.name,
                item.id,
                item.type,
                item.enableState,
                item.createAt ? moment(item.createAt).format("YYYY-MM-DD HH:mm:ss") : "",
              ]);
            },
            total: () => filteredData.totalElements
          };

          grid.updateConfig({ server }).forceRender();

        } catch (error) {
          console.error("查询数据时发生错误：", error.message);
          showToastPro("查询数据时发生错误：" + error.message);
        }
      });

      document.getElementById("dataTable").addEventListener("click", (event) => {
        if (event.target.closest(".updateRoleButton")) {
          const id = event.target.closest(".updateRoleButton").getAttribute("data-id"); // 获取角色的 id
          const role = roles.find(r => r.id == id); // 使用角色的 id 查找数据
          if (role) {
            document.getElementById("id").value = role.id;
            document.getElementById("name").value = role.name;
            document.getElementById("type").value = role.type;
            document.getElementById("enableState").value = role.enableState || '';
            new bootstrap.Modal(document.getElementById("editRoleModalEl")).show();
          }
        } else if (event.target.closest(".toggleRoleButton")) {
          const id = event.target.closest(".toggleRoleButton").getAttribute("data-id"); // 获取角色的 id
          fetch(`/api/rest/role/${id}/toggle`, { method: "PATCH" }) // 直接传入 id，无需编码
            .then(response => {
              if (response.ok) {
                document.getElementById("successMessage").innerText = "切换角色状态成功！";
                new bootstrap.Toast(document.getElementById("successToastEl")).show();
                grid.updateConfig(gridOptions).forceRender(); // 刷新表格
              } else {
                console.error("请求失败：", response.statusText);
              }
            })
            .catch(error => {
              console.error("网络错误：", error);
            });
        }
      });

      document.getElementById("editRoleModalEl").addEventListener("hidden.bs.modal", function () {
        document.body.classList.remove("modal-open"); // 确保页面不被锁定
        document.querySelector(".modal-backdrop")?.remove(); // 移除模态框的遮罩
      });

      document.getElementById("editRoleForm").addEventListener("submit", async (event) => {
        event.preventDefault();

        const formElement = document.getElementById("editRoleForm");
        if (formElement.checkValidity()) {
          const formData = Object.fromEntries(new FormData(formElement));

          // 调试打印请求体
          console.log("发送的请求体:", formData);

          try {
            let url = '/api/rest/role';
            let method = 'POST';

            // 如果是编辑模式，使用 PATCH 请求，并设置特定的 URL
            if (isEditMode) {
              url = `/api/rest/role/${formData.id}`;  // 使用表单中的 id 值
              method = 'PATCH';
            }

            const response = await fetch(url, {
              method: method,
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(formData),
            });

            if (response.ok) {
              const successMessage = isEditMode ? "角色更新成功！" : "角色创建成功！";
              document.getElementById("successMessage").innerText = successMessage;
              new bootstrap.Toast(document.getElementById("successToastEl")).show();
              bootstrap.Modal.getInstance(document.getElementById("editRoleModalEl")).hide();
              const modalElement = document.getElementById('editRoleModalEl');
              const modalInstance = bootstrap.Modal.getInstance(modalElement);
              modalInstance.hide();
              grid.updateConfig(gridOptions).forceRender(); // 刷新表格
            } else {
              const errorData = await response.json();
              console.error("请求失败：", errorData);
            }
          } catch (error) {
            console.error("网络错误：", error);
          }
        } else {
          formElement.classList.add("was-validated");
        }
      });
    };

  </script>
</body>

</html>